package cn.hnkjxy.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.hnkjxy.po.User;

public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest res, HttpServletResponse rep, Object obj) throws Exception {
		String	url = res.getRequestURI();
		if((url.indexOf("/login")>=0)||(url.indexOf("/css/")>=0)||(url.indexOf("/js/")>=0)||(url.indexOf("/register")>=0)) {
			return true;
		}
		
		HttpSession session = res.getSession();
		User user = (User) session.getAttribute("user");
		if(user != null) {
		if(url.indexOf("admin")>=0) {
			if(user.getRole().equals("管理员")) {
				return true;
			}
			res.setAttribute("msg", "您的权限不足");
			res.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(res, rep);
			return false;
			}
		}
		
		if(user != null) {
			return true;
		}
		res.setAttribute("msg", "您还未登录请先登录");
		res.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(res, rep);
		return false;
	}

}
